from sqlalchemy.orm import sessionmaker
from api.models.api_models import Admin


class AdminDAO:
    def __init__(self, engine):
        self.engine = engine
        self.Session = sessionmaker(bind=self.engine, expire_on_commit=False)

    def create(self, admin_id, user_id):
        session = self.Session()
        admin = Admin(admin_id=admin_id, user_id=user_id)
        session.add(admin)
        session.commit()
        session.close()
        return admin

    def read(self, admin_id):
        session = self.Session()
        admin = session.query(Admin).filter_by(admin_id=admin_id).first()
        session.close()
        return admin

    def update(self, admin_id, user_id=None):
        session = self.Session()
        admin = session.query(Admin).filter_by(admin_id=admin_id).first()
        if user_id is not None:
            admin.user_id = user_id
        session.commit()
        session.close()

    def delete(self, admin_id):
        session = self.Session()
        admin = session.query(Admin).filter_by(admin_id=admin_id).first()
        session.delete(admin)
        session.commit()
        session.close()